const gulp = require("gulp");
const gutil = require("gulp-util");
const sourcemaps = require("gulp-sourcemaps");

gulp.task("libs", () => {
    gulp
        .src([
            "node_modules/jquery/dist/jquery.min.js",
            "node_modules/babel-polyfill/dist/polyfill.min.js"
        ])
        .pipe(gulp.dest("../js/"));
});

gulp.task("typescript", callback => {
    const ts = require("gulp-typescript");
    const tsProj = ts.createProject("tsconfig.json", {
        outFile: "./tetris.js"
    });
    const babel = require("gulp-babel");

    const result = tsProj.src()
        .pipe(sourcemaps.init())
        .pipe(tsProj());

    return result.js
        .pipe(babel({
            presets: ["es2015", "stage-3"]
        }))
        .pipe(sourcemaps.write("../js", {
            sourceRoot: "../src/scripts"
        }))
        .pipe(gulp.dest("../js"));
});

gulp.task("less", callback => {
    const less = require("gulp-less");

    return gulp.src("./less/**/*.less")
        .pipe(sourcemaps.init())
        .pipe(less())
        .on("error", err => {
            gutil.log(err.message);
            callback();
        })
        .pipe(sourcemaps.write("../css", {
            sourceRoot: "../src/less",
            sourceMappingURL: file => `${file.relative}.map`
        }))
        .pipe(gulp.dest("../css"));
});

gulp.task("build", ["libs", "typescript", "less"]);

gulp.task("watch", () => {
    gulp.watch("./scripts/**/*.ts", { interval: 1000 }, ["typescript"]);
    gulp.watch("./less/**/*.less", { interval: 300 }, ["less"]);
});

gulp.task("default", ["watch", "build"]);
